<template>
  <div class="order_detail">
    <van-nav-bar style="margin-bottom:0;" title="订单" left-arrow @click-left="goback"/>
    <div class="order-goods">
      <van-card v-for="item in orderGoods"
                :key="item.id"
                :title="item.goodsName"
                desc="暂无描述"
                :num="item.number"
                :price="item.price +'.00'"
                :thumb="item.picUrl"></van-card>

      <van-cell-group>
        <van-cell title="商品金额">
          <span class="red">{{orderInfo.goodsPrice * 100 | yuan}}</span>
        </van-cell>
        <van-cell title="快递费用">
          <span class="red">{{orderInfo.freightPrice * 100 | yuan}}</span>
        </van-cell>
      </van-cell-group>
    </div>

    <van-cell-group style="margin-top: 20px;">
      <van-cell icon="dingwei"
                :title="`${orderInfo.consignee}  ${orderInfo.mobile}`"
                :label="orderInfo.address" />
    </van-cell-group>

    <van-cell-group style="margin-top: 20px;">
      <van-cell title="下单时间">
        <span>{{orderInfo.addTime }}</span>
      </van-cell>
      <van-cell title="订单编号">
        <span>{{orderInfo.orderSn }}</span>
      </van-cell>
      <van-cell title="订单备注">
        <span>{{orderInfo.remark }}</span>
      </van-cell>

      <van-cell title="实付款：">
        <span class="red">{{orderInfo.actualPrice * 100 | yuan}}</span>
      </van-cell>
      <!-- 订单动作 -->
      <van-cell>
        <van-button size="small"
                    v-if="handleOption.cancel"
                    @click="cancelOrder(orderInfo.id)"
                    style=" float:right"
                    round
                    type="danger">取消订单</van-button>
        <van-button size="small"
                    v-if="handleOption.pay"
                    @click="payOrder(orderInfo.id, orderInfo.payType, orderInfo.hbFqNum)"
                    style=" float:right"
                    round
                    type="danger">去支付</van-button>
        <van-button size="small"
                    v-if="handleOption.delete"
                    @click="deleteOrder(orderInfo.id)"
                    style=" float:right"
                    type="danger">删除订单</van-button>
        <van-button size="small"
                    v-if="handleOption.confirm"
                    @click="confirmOrder(orderInfo.id)"
                    style=" float:right"
                    type="danger">确认收货</van-button>
        <van-button size="small"
                    v-if="handleOption.refund"
                    @click="refundOrder(orderInfo.id)"
                    style=" float:right"
                    type="danger">退款</van-button>
      </van-cell>
    </van-cell-group>

    <van-cell-group v-if="showExp()"
                    style="margin-top: 20px;">
      <van-cell title="快递公司">
        <span>{{orderInfo.expCode }}</span>
      </van-cell>
      <van-cell title="快递编号">
        <span>{{orderInfo.expNo }}</span>
      </van-cell>
    </van-cell-group>

    <van-cell-group v-if="handleOption.comment" style="margin-top: 20px;">
      <van-cell title="开票状态">
        <span style="color: red;">{{invoiceStatus?'已开票':'未开票' }}</span>
      </van-cell>

      <div v-if="!invoiceStatus" style="padding: 10px 0;text-align: center;">
        <van-button @click="kp(orderInfo.id, 1)" plain style="margin-right: 10px;" >专用发票</van-button>
        <van-button @click="kp(orderInfo.id, 0)" plain >普通发票</van-button>
      </div>
      <div v-else style="padding: 10px 0;text-align: center;">
        <van-button @click="receiptOrderc(orderInvoice)" plain >取消开票</van-button>
      </div>
    </van-cell-group>
    <van-dialog v-model="kpShow" title="开票信息" show-cancel-button @confirm="clickKp(orderInfo.id)">
     <div class="kltit">是否申请开具增值税{{typeName}}发票，一经开具无法修改！</div>
     <van-cell-group style="overflow-y:scroll;max-height: 400px;">
        <van-field v-model="kpData.sName" label="收件人：" placeholder="请输入收件人" />
        <van-field v-model="kpData.sMobile" label="收件电话：" placeholder="请输入收件电话" />
        <van-field v-model="kpData.sAddress" label="收件地址：" placeholder="请输入收件地址" />
        <van-cell title="企业：" :value="kpData.name" />
        <van-cell title="地址：" :value="kpData.address" />
        <van-cell title="电话：" :value="kpData.mobile" />
        <van-cell title="纳税人识别号：" :value="kpData.licenseNumber" />
        <van-cell title="开户行：" :value="kpData.bank" />
        <van-cell title="银行账号：" :value="kpData.bankNumber" />
      </van-cell-group>
    </van-dialog>
  </div>
</template>

<script>
import { Card, Field, SubmitBar, Button, Cell, CellGroup, Dialog, NavBar } from 'vant';
import { getLocalStorage, setLocalStorage } from '@/utils/local-storage';
import _ from 'lodash';
import {
  orderAlipay,
  orderPrepay,
  invoiceApplyInvoice,
  invoiceCancelInvoice,
  invoiceDetail,
  orderDetail,
  orderRepay,
  orderDelete,
  orderConfirm,
  orderCancel,
  orderRefund,
  orderPayByQuickApply
} from '@/api/api';

export default {
  data() {
    return {
      kpShow: false,
      typeName: '',
      kpData: {
        sName: '',
        sMobile: '',
        sAddress: '',
        name: '',
        address: '',
        mobile: '',
        licenseNumber: '',
        bank: '',
        bankNumber: ''
      },
      isSubmit: false,
      isDisabled: false,
      invoiceStatus: '',
      orderInvoice: '',
      orderInfo: {},
      orderGoods: [],
      handleOption: {},
      expressInfo: {}
    };
  },
  created() {
    this.init();
  },

  methods: {
    showExp() {
      return _.has(this.orderInfo, 'expNo');
    },
    clickKp(id) {
      if(this.kpData.sName === '') {
        this.$toast('请填写收货人名称');
        return false
      }
      if (this.kpData.sMobile === '') {
        this.$toast('请填写正确的收货人电话');
        return false
      }
      if(this.kpData.sAddress === '') {
        this.$toast('请填写收货人地址');
        return false
      }
      let type = 0;
      if(this.typeName === '专用') {
        type = 1
      } else if(this.typeName === '普通') {
        type = 0
      }
      invoiceApplyInvoice({ orderId: id, type: type, consignee: this.kpData.sName, mobile: this.kpData.sMobile, deliveryAddress: this.kpData.sAddress }).then(res => {
        if (res.data.errno === 0) {
          this.$toast('申请成功');
          this.$router.push('/user');
        } else {
          this.$Tosat('申请失败');
        }
      });
      // console.log(this.kpData)
    },
    kp(id, type) {
      if(type === 1) {
        this.typeName = '专用'
      } else if(type === 0) {
        this.typeName = '普通'
      }
      invoiceDetail().then(res => {
        if(res.data.errno !== 0 || !res.data.data.invoice.id) {
          this.$toast('暂无开票信息，请先添加');
          this.$router.push('/user/zizhistore');
          return false;
        } else {
          // console.log(res)
          this.kpShow = true
          this.kpData.name = res.data.data.invoice.name
          this.kpData.mobile = res.data.data.invoice.phone
          this.kpData.address = res.data.data.invoice.address
          this.kpData.licenseNumber = res.data.data.invoice.licenseNumber
          this.kpData.bank = res.data.data.invoice.bank
          this.kpData.bankNumber = res.data.data.invoice.bankNumber
          // this.$dialog.confirm({ message: '是否申请开具增值税'+typeName+'发票，一经开具无法修改！' }).then(() => {
          //   invoiceApplyInvoice({ orderId: id, type: type }).then(res => {
          //     if (res.data.errno === 0) {
          //       this.$toast('申请成功');
          //       this.$router.go(-1);
          //     } else {
          //       this.$Tosat('申请失败');
          //     }
          //   });
          // }).catch(() => {});
        }
      })
      
    },
    receiptOrderc(id) {
      this.$dialog
        .confirm({ message: '是否取消申请开具增值税发票！' })
        .then(() => {
          invoiceCancelInvoice({ orderInvoiceId: id }).then(res => {
            if (res.data.errno === 0) {
              this.$toast('取消成功');
              this.$router.go(-1);
            } else {
              this.$Tosat('取消失败');
            }
          });
        })
        .catch(() => {});
    },
    goback() {
      this.$router.go('-1');
      // this.$router.push({ path: '/user/order/list/0' });
    },
    deleteOrder(id) {
      let that = this;
      this.$dialog
        .confirm({ message: '确定要删除该订单吗?' })
        .then(() => {
          orderDelete({ orderId: id }).then(() => {
            this.$toast('已删除订单');
            this.$router.go(-1);
          });
        })
        .catch(() => {});
    },
    cancelOrder(id) {
      this.$dialog
        .confirm({ message: '确定要取消该订单吗?' })
        .then(() => {
          orderCancel({ orderId: id }).then(() => {
            this.init();
            this.$toast('已取消该订单');
            this.$router.go(-1);
          });
        })
        .catch(() => {});
    },
    payOrder(id, payType, hbFqNum) {
      this.$dialog
        .confirm({ message: '确定要支付该订单吗?' })
        .then(() => {
          if(payType === '支付宝支付' || payType === '花呗分期') {
          orderAlipay({orderId: id, payType: payType, hbFqNum: hbFqNum}).then(res => {
            if(res.data.errno === 0) {
              cordova.plugins.alipay.payment(res.data.data, (e) => {
                this.$toast('支付成功')
                // 支付成功
                this.$router.push('/user/order/list/2')
              }, (e) => {
                // TODO 支付失败
                // console.log('支付失败' + e.resultStatus)
                this.$toast('支付失败')
                this.$router.push('/user')
              })

            } else if (res.data.errno === 1) {
              this.$router.push({
                name: 'payment',
                params: { orderId: id }
              });
            } else {
              this.isDisabled = false;
              this.$toast(res.data.errmsg);
            }
          })
          }else if(payType === '微信支付'){
             orderPrepay({orderId: id, payType: payType}).then(res => {
              // console.log(res, 'weichat')
              if(res.data.errno === 0) {
                var params = {
                  appid: res.data.data.appId, // appId
                  partnerid: res.data.data.partnerId, // merchant id
                  prepayid: res.data.data.prepayId, // prepay id
                  noncestr: res.data.data.nonceStr, // nonce
                  backage: 'Sign=WXPay',
                  timestamp: res.data.data.timeStamp, // timestamp
                  sign: res.data.data.sign // signed string
                }
                window.Wechat.sendPaymentRequest(params, function () {
                  this.$toast('支付成功')
                }, function (reason) {
                  this.$toast('Failed: ' + reason)
                  this.$router.push('/user/order/list/1')
                })
              } else if (res.data.errno === 1) {
                this.$toast('支付成功')
                this.$router.push('/user/order/list/2')
              } else {
                this.isDisabled = false;
                this.$toast(res.data.errmsg);
              }
            })
          } else if(payType === '通联快捷通道支付') {
              var params = {
                  orderId : id,
                  orderSource : 'APP'
                }
              orderPayByQuickApply(params).then(info => {
                // console.log(info)
                if (info.data.data.resultCode === '1999')
                {
                  setLocalStorage({orderId: id});
                  setLocalStorage({thpinfo: info.data.data.thpinfo});
                  this.$router.push('/order/smsConfirm')
                }
              })
          }
          // orderRepay({orderId: id}).then(res => {
          //   this.init();
          //   this.$toast('已成功支付');
          //   this.$router.push({ path: '/user/order/list/0' });
          // });
        })
        .catch(() => {});
    },
    confirmOrder(id) {
      this.$dialog
        .confirm({
          message: '请确认收到货物, 确认收货后无法撤销!'
        })
        .then(() => {
          orderConfirm({ orderId: id }).then(() => {
            this.init();
            this.$toast('已确认收货');
            this.$router.go(-1);
          });
        })
        .catch(() => {});
    },
    refundOrder(id) {
      this.$dialog
        .confirm({ message: '确定要申请退款吗?' })
        .then(() => {
          orderRefund({ orderId: id }).then(() => {
            this.init();
            this.$toast('已申请订单退款');
            this.$router.go(-1);
          });
        })
        .catch(() => {});
    },
    commentOrder(id) {},
    toPay(id) {
      this.$router.push({ name: 'payment', params: { orderId: id } });
    },
    init() {
      let orderId = this.$route.query.orderId;
      orderDetail({ orderId: orderId }).then(res => {
        var data = res.data.data;
        // console.log(data.invoiceStatus)
        this.invoiceStatus = data.invoiceStatus
        this.orderInvoice = data.orderInvoice
        this.orderInfo = data.orderInfo;
        this.orderGoods = data.orderGoods;
        this.handleOption = data.orderInfo.handleOption;
        this.expressInfo = data.expressInfo;
        this.kpData.sName = data.orderInfo.consignee;
        this.kpData.sMobile = data.orderInfo.mobile;
        this.kpData.sAddress = data.orderInfo.address;
      });
    }
  },

  components: {
    [NavBar.name]: NavBar,
    [Dialog.Component.name]: Dialog.Component,
    [Dialog.name]: Dialog,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Button.name]: Button,
    [SubmitBar.name]: SubmitBar,
    [Card.name]: Card,
    [Field.name]: Field
  }
};
</script>


<style lang="scss" scoped>
.order_detail {
  padding-bottom: 70px;
}
.van-button {
  margin: 0 2px;
}
.kltit {
  color: #ff6600;
  padding: 5px 16px;
}
</style>
